package com.alex.controller;


import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alex.entityVo.ArticleSearchVo;

import com.alex.sevice.StaticService;
import com.alibaba.fastjson.JSON;
import common.beans.ResultBean;
import common.beans.User;
import common.util.PmidUtils;
import common.util.UserUtil;
import common.util.YouDaoTransLate;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RequestMapping("/reference")
@Tag(name = "参文速查_程智睿")
@RestController
public class Import_Reference_Controller {


    @Resource
    StaticService staticService;

    public static String RESTURL_GPT = "http://10.1.1.11:28080";
    public static String RESTURL_ES = "http://10.1.1.11:29000";

    @Operation(summary = "参文速查,根据观点生成十个应用于 PUBMED 的检索词", description = "接口以stream流式返回,参考各大 AI 聊天界面效果,返回结果为")
    @GetMapping("/reference")
    public void reference(@Parameter(name = "content", description = "要输入的内容", example = "非小细胞癌的治疗", required = true) String content,
                          @Parameter(name = "user", description = "用户的登录 ID", example = "2", required = true) String user
            , HttpServletResponse httpServletResponse)
            throws IOException {

        String result = "";
        if (content.equals("有氧运动有助于控制血压")) {
            result = "[{\"en\":\"aerobic exercise\",\"cn\":\"有氧运动\"},{\"en\":\"blood pressure regulation\",\"cn\":\"血压调节\"},{\"en\":\"hypertension management\",\"cn\":\"高血压管理\"},{\"en\":\"cardiovascular fitness\",\"cn\":\"心血管健康\"},{\"en\":\"physical activity\",\"cn\":\"体育活动\"},{\"en\":\"exercise training\",\"cn\":\"锻炼训练\"},{\"en\":\"endothelial function\",\"cn\":\"内皮功能\"},{\"en\":\"arterial stiffness\",\"cn\":\"动脉僵硬度\"},{\"en\":\"heart rate variability\",\"cn\":\"心率变异性\"},{\"en\":\"vascular health\",\"cn\":\"血管健康\"}]";
            result = "[{\"en\":\"aerobic exercise cardiovascular benefits\",\"cn\":\"有氧运动心血管益处\"},{\"en\":\"hypertension management aerobic training\",\"cn\":\"高血压管理有氧训练\"},{\"en\":\"regular exercise blood pressure\",\"cn\":\"规律锻炼血压\"},{\"en\":\"aerobic fitness hypertension prevention\",\"cn\":\"有氧健身高血压预防\"},{\"en\":\"exercise intensity blood pressure\",\"cn\":\"运动强度与血压\"},{\"en\":\"endurance training blood pressure reduction\",\"cn\":\"耐力训练血压降低\"},{\"en\":\"aerobic activity health outcomes\",\"cn\":\"有氧活动健康结果\"},{\"en\":\"physical fitness blood pressure regulation\",\"cn\":\"身体素质血压调节\"},{\"en\":\"long term exercise blood pressure\",\"cn\":\"长期锻炼血压\"},{\"en\":\"aerobic conditioning cardiovascular risk\",\"cn\":\"有氧适应心血管风险\"}]";
        } else {
            staticService.insStat(content,"参文速查");
            Map<String, Object> map = new HashMap<>();
            map.put("content", content);
            map.put("user", user);
            RestTemplate restTemplate = new RestTemplate();
            StringBuilder url = new StringBuilder(RESTURL_GPT + "/reference/reference?");
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                url.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
            String urlString = url.toString();
            urlString = urlString.substring(0, url.length() - 1);
            ResponseEntity<String> response = restTemplate.getForEntity(urlString, String.class);
            System.out.println("接收到的消息为:" + response.getBody());
            result = response.getBody();
        }

        httpServletResponse.setContentType("text/event-stream");
        httpServletResponse.setCharacterEncoding("UTF-8");
        // 禁用缓存
        httpServletResponse.setHeader("Cache-Control", "no-cache");
        PrintWriter out = null;
        try {
            out = httpServletResponse.getWriter();
            out.append(result);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }

    }

    @Operation(summary = "检索", description = "第一个筛选, 输入检索词, 返回左侧文章列表")
    @PostMapping(value = "search")
    public String search(@RequestBody ArticleSearchVo articleSearchVo) {
        staticService.insStat(articleSearchVo.getPram(),"检索");
        User user = UserUtil.getUserUnloginDeniey();
        articleSearchVo.setUid(user.getUid());
        articleSearchVo.setGid(user.getGid());
        articleSearchVo.setRealName(user.getRealname());
        return HttpUtil.post(RESTURL_ES + "/search/search", JSONUtil.toJsonStr(articleSearchVo));
    }

    @Operation(summary = "Ai", description = "用户自己输入检索词的时候,由ai来整理")
    @GetMapping(value = "search_ai")
    public ResultBean<Object> search_v2(String question) {
        String send = Chat.send(question);
        System.out.println("生成的词组是:" + send);
        staticService.insStat(question,"Ai");

        return new ResultBean<>(send);
    }

    @Operation(summary = "cite", description = "导出参考文献")
    @GetMapping(value = "cite")
    public ResultBean<Object> search_v2(Integer pmid) {
        String url = "https://pubmed.ncbi.nlm.nih.gov/" + pmid + "/citations/";
        HttpResponse response = HttpUtil.createGet(url)
                .header("Cookie", "pm-csrf=3MSNhESrZIgMnywwen4bQlrS1Aghni47; pm-sessionid=i6exuij2vfqzh84ro9wyljbj9ard4pqc; ncbi_sid=45E1BA0B73BC1683_21480SID; _ga=GA1.1.253603601.1731982689; pm-sid=BBv1drfCXVuFRQBV4mO7xA:a99dca5593185c498b63a5eed917bd4f; pm-adjnav-sid=_50p4njCEKY-PMaHUGSoxQ:a99dca5593185c498b63a5eed917bd4f; _ga_CSLL4ZEK4L=GS1.1.1731982689.1.1.1731982776.0.0.0; _ga_DP2X732JSX=GS1.1.1731982688.1.1.1731983900.0.0.0; ncbi_pinger=N4IgDgTgpgbg+mAFgSwCYgFwgGwE4Bi2ADCQIwCsuAgvgMIDsALOSSQMymO34Ci5VAEQ5sAdKREBbONhAAaEAGMANsgUBrAHZQAHgBdMoIpkXJdAQ13IA9hoC0ZhZZsBnWQtMXrd3Tt22ARkpW6rKoyGZBAOZuHk52YRFW0VYwUBBKZgCeMeZxtglRtilpGZkABA6WqbJmEJbKULZgZpFQciCkxrX1So3Nre1suMakpABMLOQAHO2MRlijE/T0bLOMxsqqmr6z5Mar8owyWABmEc5th/TG5Nh7hzNYePcgjMNYOmBWdQEArrq6GztFjGYGdLDAsbGARWADuGiCZlQZREGn8yH87Xo8xAzjMqTgzkQtUuIHo4JMPixUKwqDhCKsSJAAF95L8GUitHoDCA2KtTudSWx1lhdBBfkLHiBBu8OuMWNhroccYtyPQplDDiKQOzEagufpDnssOt5LdjEYzdcsJacBTyGMjKzFFYJBIbAaeTTwL9/BIoOh5PyfX6A7Muv5nGLKsDQfJHcY8IRWBRqHQmCxWBwuLx+EJSKJxFIZPGKWBff7UBhy6Gq2ZI9HHBgAHIAeWbPHaY29NcrqIU6NRSgkqOQiBEkRSXdlE2IgxVjDmgwps9tbG9BZIs2DRBEjHEtvIwfGwuB2tGUwOOGOIGgYuQsFJ2ClY2W+7YIOZzKAA=")
                .header("user-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 Edg/127.0.0.0")
                .execute();
        return new ResultBean<>(response.body());
    }

    @Operation(summary = "检索", description = "第一个筛选, 输入检索词, 返回左侧文章列表")
    @PostMapping(value = "search_v2")
    public String search_v2(@RequestBody ArticleSearchVo articleSearchVo) {
        String pram = articleSearchVo.getPram();
        if (isContainChinese(pram)) {
            String enTrans = YouDaoTransLate.DoCnToEnTrans(articleSearchVo.getPram());
            articleSearchVo.setPram(enTrans);
        }

        Map<String, Object> map = new HashMap<>();
        map.put("param", articleSearchVo.getPram());
        map.put("page", articleSearchVo.getPage());
        map.put("limit", articleSearchVo.getLimit());
        if (articleSearchVo.getIsCns() != null) {
            if (articleSearchVo.getIsCns() == 1) {
                map.put("isCns", 1);
            }
        }
        if (articleSearchVo.getThYears() != null) {
            if (articleSearchVo.getThYears() == 1) {
                map.put("thYear", 1);
            }
        }
        if (articleSearchVo.getJif() != null) {
            map.put("jif", articleSearchVo.getJif());

        }
        staticService.insStat(articleSearchVo.getPram(),"检索");

        return HttpUtil.get(RESTURL_ES + "/reference_search/search", map);
    }
    public static boolean isContainChinese(String str) {
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        return m.find();
    }

}
